// Copyright 2013 The golog2bq Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// +build appengine

package log2bq

import (
	"appengine"
	"appengine/urlfetch"
	"errors"
	"net/http"
	"time"
)

var (
	ErrInvalidToken = errors.New("Invalid Access Token")
	ErrExpiredToken = errors.New("Expired Access Token")
	ErrNilTransport = errors.New("Transport is nil")
)

type Transport struct {
	Token     string
	Expiry    time.Time
	Transport http.RoundTripper
}

func GAETransport(c appengine.Context, scopes ...string) (*Transport, error) {
	var err error
	t := &Transport{}
	t.Token, t.Expiry, err = appengine.AccessToken(c, scopes...)
	if err != nil {
		return t, err
	}
	t.Transport = &urlfetch.Transport{
		Context: c,
	}
	return t, nil
}

func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
	if t.Token == "" {
		return nil, ErrInvalidToken
	}
	if time.Now().After(t.Expiry) {
		return nil, ErrExpiredToken
	}
	if t.Transport == nil {
		return nil, ErrNilTransport
	}
	req2 := new(http.Request)
	*req2 = *req
	req2.Header = make(http.Header)
	for k, s := range req.Header {
		req2.Header[k] = s
	}
	req2.Header.Set("Authorization", "Bearer "+t.Token)
	return t.Transport.RoundTrip(req2)
}

func (t *Transport) Client() (*http.Client, error) {
	if t.Transport == nil {
		return nil, ErrNilTransport
	}
	return &http.Client{Transport: t}, nil
}
